<template>
  <div>
    <!-- 面包屑 -->
    <!-- 面包屑 -->
    <el-breadcrumb separator="/" style="font-size: 12px">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- <MBX level1="商品管理" level2="添加商品"></MBX> -->
    <!-- 主体区域 -->
    <el-card style="margin-top: 15px">
      <el-alert
        center
        :closable="false"
        title="消息提示的文案"
        type="info"
        show-icon
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        align-center
        class="mt16 aa"
        :active="active * 1"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单 -->
      <el-form :model="addGoodsForm">
        <!-- tab栏 -->
        <el-tabs
          class="mt16"
          tab-position="left"
          v-model="active"
          @tab-click="handleClick"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>

            <el-form-item label="商品重量">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>

            <el-form-item label="商品数量">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类">
              <!-- 商品分类级联框 -->
              <!-- 
                1.v-model:当前选中项数组
                2.options：级联选择框数据源 
                3.props：级联框的默认配置项
                4.change:级联框分类改变时触发
               -->
              <!-- <p>{{ current_select_arr }}---{{ current_cate_id }}</p> -->
              <el-cascader
                v-model="current_select_arr"
                :options="cateData"
                :props="defaultProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染动态商品参数 -->
            <el-form-item
              :label="item1.attr_name"
              v-for="item1 in manyParams"
              :key="item1.id"
            >
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox
                  :label="item2"
                  v-for="(item2, index) in item1.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParams"
              :key="item.id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                <!-- 只能上传jpg/png文件，且不超过500kb -->
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" />
            <el-button type="primary" class="mt16" @click="addGoodsOk"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "goodsadd",
  data() {
    return {
      //设置请求头
      headers: {
        Authorization: sessionStorage.getItem("token"),
      },
      //级联框数据源
      cateData: [],
      //当前选中的分类级别
      current_select_arr: [],
      //级联框默认配置
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      active: "0",
      //要提交的商品表单数据
      addGoodsForm: {
        //商品名称
        goods_name: "",
        //商品分类
        goods_cat: "",
        //商品价格
        goods_price: 0,
        //商品数量
        goods_number: 0,
        //商品重量
        goods_weight: 0,
        // //商品介绍
        goods_introduce: "",
        //图片上传数组 [{pic:'xxx'}]
        pics: [],
        //商品参数,包括动态参数和静态参数
        attrs: [],
      },
      //动态参数
      manyParams: [],
      //静态参数
      onlyParams: [],
    };
  },
  created() {
    this.getGoodsCateList();
  },
  methods: {
    async addGoodsOk() {
      console.log("addGoodsOk:", this.addGoodsForm);
      //处理分类数组为字符串
      this.addGoodsForm.goods_cat = this.current_select_arr.join(",");

      //动态参数处理
      const dtData = this.manyParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(","),
        };
      });

      //静态参数处理
      const jtData = this.onlyParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
      });

      //合并静态和动态参数
      const mergeParams = [...dtData, ...jtData];
      //将合并的结果赋值给attrs
      this.addGoodsForm.attrs = mergeParams;

      console.log("最终提交结果:", this.addGoodsForm);

      //将this.addGoodsForm对象进行深拷贝，再将深拷贝后的对象传递给后台
      const allGoodsData = _.cloneDeep(this.addGoodsForm);

      //开始调添加商品接口提交数据
      const res = await this.$API.addGoodsApi(allGoodsData);
      console.log("添加成功", res);
      //添加完商品跳转到商品列表页，查看添加的商品
      this.$router.push("/goods");
    },
    //触发预览效果
    handlePreview() {},
    //上传成功
    handleSuccess(res) {
      console.log("上传成功：", res);
      this.addGoodsForm.pics.push({ pic: res.data.tmp_path });
      console.log(" this.addGoodsForm.pics:", this.addGoodsForm.pics);
    },
    //删除上传
    handleRemove(res) {
      console.log("删除成功：", res);
      const index = this.addGoodsForm.pics.findIndex((item) => {
        return item.pic === res.response.data.tmp_path;
      });

      this.addGoodsForm.pics.splice(index, 1);
      console.log("删除成功：", this.addGoodsForm.pics);
    },
    //tab切换之前做是否阻止到下一步的处理
    beforeLeave(newActive, oldActive) {
      if (oldActive === "0" && this.current_select_arr.length !== 3) {
        this.$message({
          type: "error",
          message: "请选择三级分类之后，才能进行下一步的操作！！！！",
        });

        return false;
      }
    },
    //商品分类
    async getGoodsCateList() {
      const res = await this.$API.getGoodsCateListApi();
      console.log("商品分类：", res);
      this.cateData = res;
    },

    async handleClick() {
      console.log(this.active);

      if (this.active === "1") {
        //调取动态参数接口
        const res = await this.$API.getGoodsParamsApi(this.current_cate_id);

        res.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });

        console.log("动态参数：", res);
        this.manyParams = res;
      } else if (this.active === "2") {
        //调取静态参数接口
        //调取动态参数接口
        this.onlyParams = await this.$API.getGoodsParamsApi(
          this.current_cate_id,
          "only"
        );

        console.log("静态参数：", this.onlyParams);
      }
    },
    handleChange() {},
  },
  computed: {
    current_cate_id() {
      return this.current_select_arr[this.current_select_arr.length - 1];
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-step__title {
  font-size: 12px !important;
}
::v-deep .ql-editor {
  height: 300px;
}
</style>
